/**
 * Created by dong on 15/11/9.
 * 对打包后的bar进行处理
 * 将bar按目录放置, 后期考虑放到阿里云云
 *
 *
 */
    'use strict';

var fs = require('fs');
var fse = require('fs-extra');
var path = require('path');


// 使用本地的, 或者是阿里云的.
var baseDir ='/barRepo/';


var transferOrder;
let widgetMap;
function bundleFileDeal(params){
    //params.isTransferOss =false; //是否传到阿里云上
    //params.transferOrder ='bundle-test'
    //console.dir(params);
    console.log('打包即将开始,将要清空barBuild文件夹下的所有文件!~');
    fse.emptyDirSync('./barBuild');
    console.log('成功清空barBuild文件夹!');
    widgetMap= params.widgetMap;
    //process.exit(0);
}


module.exports=bundleFileDeal;

bundleFileDeal.prototype.apply = function (compiler) {
    compiler.plugin('done', function(stats) {
        console.log(' 打包结束 开始处理bundle文件');
        //把对应的文件放到对应的位置云.

        //setTimeout(()=>{
            for(let ns  in widgetMap){
                let widgetInfo  =  widgetMap[ns];
                mvFile(widgetInfo)
            }
        //},100000);
        console.log(' bundle文件处理完成');
        //fse.outputFileSync('../auto/bundle-map.js',   generateMap(stats.toJson().assetsByChunkName));
    });
}


/**
 *
 * @param widgetInfo
 {
 jsFilename:"",
 cssfilename:"",
 widgetName:"",
 widgetNameSpace:"",
 }
 */
function mvFile(widgetInfo){
    
    let jsfilePath  = path.join(__dirname,'../../dist/barBuild',widgetInfo.jsFilename);
    let cssFilePath   = path.join(__dirname,'../../dist/barBuild',widgetInfo.cssfilename);
    let widgetPath  =  path.join(__dirname,'../../dist/barRepo',widgetInfo.widgetNameSpace);

    fse.move(jsfilePath, widgetPath+".js",  {clobber:true},function (err) {
        if (err){
            console.error(err)
            console.dir(widgetInfo);
            return;
        }
    });

    fse.move(cssFilePath, widgetPath+".css", {clobber:true},function (err) {
        if (err){
            //console.error(err)
            //console.dir(widgetInfo);
            return;
        }
    });
}

